package cn.shop.merchant.controller.media;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.shop.merchant.model.media.Banner;
import cn.shop.merchant.req.MediaQueryReq;
import cn.shop.merchant.service.BannerService;
import cn.shop.thiredparty.entity.Metadata;
import cn.shop.thiredparty.service.AliOssService;
import cn.shop.utils.ApiResult;
import cn.shop.utils.annotation.OperationLog;
import cn.shop.utils.enums.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import static cn.shop.utils.constant.Constant.UID;

/**
 * 广告图相关接口
 *
 * @author : 李一涵
 * @date : Created in 2021-11-4 11:02
 * @description :
 */
@Slf4j
@SaCheckLogin
@RestController
@RequestMapping("/banner")
public class BannerController {

    @Resource
    private BannerService bannerService;
    @Resource
    private AliOssService ossService;


    /**
     * 获取广告图列表
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("")
    public ApiResult<Map<String, Object>> list(MediaQueryReq req) {
        long uid = StpUtil.getSession().getLong(UID);
        Map<String, Object> data = bannerService.list(req, uid);
        return ApiResult.success(data);
    }

    /**
     * 保存广告图
     *
     * @param file 广告图
     * @return 返回结果
     */
    /*@PostMapping("")
    @OperationLog(desc = "新增广告图", type = OperationType.CREATE)
    public ApiResult<Map<String, Object>> insert(@Validated @RequestBody Banner banner) {
        boolean isSuccess = bannerService.save(banner);
        return ApiResult.result(isSuccess);
    }*/
    @PostMapping("")
    @OperationLog(desc = "新增广告图", type = OperationType.CREATE)
    public ApiResult<Map<String, Object>> insert(@RequestParam MultipartFile file) {
        long uid = StpUtil.getSession().getLong(UID);
        //不是图片的处理
        if(!isImage(file.getOriginalFilename())){
            return ApiResult.fail("文件不是图片");
        }

        //图片大小不超过5MB
        if(file.getSize()/1024/1024 >= 5){
            return ApiResult.fail("图片大小不能超过5M");
        }
        Metadata metadata = new Metadata();
        metadata.setFilename(file.getOriginalFilename());
        metadata.setContentType(file.getContentType());
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.warn("获取图片文件流失败", e);
        }

        String filename = ossService.upload(metadata, inputStream);
        if (StrUtil.isBlank(filename)) {
            return ApiResult.fail("上传图片失败");
        }
        Banner banner = new Banner();
        banner.setPicture(filename);
        banner.setUid(uid);
        boolean isSuccess = bannerService.save(banner);
        return ApiResult.result(isSuccess);
    }

    /**
     * 更新广告图
     *
     * @param banner 广告图
     * @return 返回结果
     */
    @PutMapping("")
    @OperationLog(desc = "修改广告图", type = OperationType.UPDATE)
    public ApiResult<Map<String, Object>> update(@RequestBody Banner banner) {
        long uid = StpUtil.getSession().getLong(UID);
        boolean isSuccess = bannerService.update(banner, uid);
        return ApiResult.result(isSuccess);
    }

    /**
     * 删除广告图
     *
     * @param ids 编号
     * @return 返回结果
     */
    @PostMapping("/delete")
    @OperationLog(desc = "删除广告图", type = OperationType.DELETE)
    public ApiResult<Map<String, Object>> delete(@RequestBody List<Long> ids) {
        long uid = StpUtil.getSession().getLong(UID);
        if (uid == 0) {
            return ApiResult.fail("请检查登录状态");
        }
        boolean isSuccess = bannerService.delete(ids, uid);
        return ApiResult.result(isSuccess);
    }

    /**
     * 获取广告图信息
     *
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public ApiResult<Map<String, Object>> info(@PathVariable("id") long id) {
        long uid = StpUtil.getSession().getLong(UID);
        if (uid == 0) {
            return ApiResult.fail("请检查登录状态");
        }
        Map<String, Object> data = bannerService.info(id, uid);
        return ApiResult.success(data);
    }

    private boolean isImage(String originalFilename) {
        if (originalFilename == null)
            return false;
        if(originalFilename.contains(".")){
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileExt = fileExt.toLowerCase();
            return fileExt.equals(".jpg")
                    || fileExt.equals(".jpeg")
                    || fileExt.equals(".gif")
                    || fileExt.equals(".png")
                    || fileExt.equals(".bmp");
        }
        return false;
    }
}
